/**
 * @file easy_fsmc.c
 * @author your name (you@domain.com)
 * @brief fsmc
 * @version 0.1
 * @date 2023-08-06
 * 
 * @copyright Copyright (c) 2023
 * 
 */

/******************************* Includes ********************************/
#include "easy_fsmc.h"


/******************************* Macros ******************************/


/******************************* Typedef ******************************/


/******************************* Variables ******************************/

/******************************* Functions ******************************/
fsm_handle_t *easy_fsm_init(fsm_status_t  *fsmtb, FSMC_EVENT init_event, FSMC_STATE init_state, int count)
{
    fsm_handle_t *handle = (fsm_handle_t *)malloc(sizeof(fsm_handle_t));
    if(handle == NULL)
    {
        FSMC_E("handle malloc fail\n");
        return NULL;
    }

    memset(handle, 0, sizeof(fsm_handle_t));
    handle->fsmtb = fsmtb;
    handle->cur_event = init_event;
    handle->cur_sta = init_state;
    handle->sta_max_n = count;

    return handle;
}

int easy_fsm_process(fsm_handle_t *handle)
{
    int i = 0;
    int count = 0;
    if(handle == NULL || handle->fsmtb == NULL)
    {
       FSMC_E("handle is null\n"); 
       return 0;
    }

    count = handle->sta_max_n;
    fsm_status_t  *fsmtb = handle->fsmtb;

    for(i = 0; i < count; i++)
    {
        if(fsmtb[i].cur_sta == handle->cur_sta && fsmtb[i].event == handle->cur_event)
        {
           fsmtb[i].event_action(fsmtb[i].event, fsmtb[i].usrdata);
           handle->cur_sta = fsmtb[i].next_sta;
           //handle->cur_event = 0xFFFFFFFF;
           break;
        }
    }

    return 0;
}

int easy_fsm_event_set(fsm_handle_t *handle, FSMC_EVENT event)
{
    if(handle == NULL)
    {
       FSMC_E("handle is null\n"); 
       return 0;
    }

    handle->cur_event = event;

    return 0;
}

int easy_fsm_deinit(fsm_handle_t *handle)
{
     if(handle != NULL)
     {
        free(handle);
     }
 
     return 0;
}

/******************************* End of file ******************************/